<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="wrap"></div>
    <script type="text/html" id="template">
      <div>姓名:{{name}}</div>
      <div>年龄:{{ age}}</div>
      <div>学校:{{ school }}</div>
    </script>
    <script>
      // var template = '<div>我是{{name}},我的年龄是{{age}},我的学校是{{school}}</div>'
      // var pattern = /{{([a-zA-Z]+)}}/
      // let patternResult = null
      // while(patternResult = pattern.exec(template)){
      //   template = template.replace(patternResult[0],data[patternResult[1]])
      // }
      // console.log(template);
      var data = {
        name: "李坤",
        age: 20,
        school: "江西农业大学",
      };
      var str = template("template", data);
      document.getElementById("wrap").innerHTML = str;

      function template(id, data) {
        let element = document.getElementById(id).innerHTML;
        let pattern = /{{\s*([a-zA-Z]+)\s*}}/;
        let patternResult = null;
        while ((patternResult = pattern.exec(element))) {
          element = element.replace(patternResult[0], data[patternResult[1]]);
        }
        return element;
      }
    </script>
  </body>
</html>
